package eu.nikoladichev.test.utils;

import java.util.Calendar;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class JndiIntialContextUtil {

	static Logger logger = Logger.getLogger(JndiIntialContextUtil.class.getSimpleName());
	
	@Resource(mappedName = "java:/ConnectionFactory")
	private static ConnectionFactory connectionFactory;
	
	public static Object getIntialContext(String jndiName) throws NamingException {
		Object o = null;
		try {
			InitialContext context = new InitialContext();
			o = context.lookupLink(jndiName);
		} catch (NamingException ne) {
			logger.warning(ne.getMessage());
			throw ne;
		}
		return o;
	}
	
	public static void sendMessage(Message msg, String destinationQueue) {
		Connection connection = null;
		try {
			Queue destQueue = (Queue) getIntialContext(destinationQueue);
			connection = connectionFactory.createConnection();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer messageProducer = session.createProducer(destQueue);
			messageProducer.send(msg);
			logger.info("This message was sent to queue \"" + destinationQueue + "\" and it was sent at " + Calendar.getInstance().getTime().toString() + ".");
		} catch (Exception e) {
			logger.warning(e.getMessage());
		}
	}
}
